#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
THN WEB SERVER

Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

This library is dual-licensed.
  + For use in commercial software, please obtain a commercial license from THN Solutions LLC.    

  + For use in free software, this library is licensed under GPL version 3. A summary of 
	GPLv3 is listed below. You should also find a copy of GPLv3 as file License_GPLv3.txt 
	included with the source-code files.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 3 as published by
    the Free Software Foundation  of the License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 05-Sep-12 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;
using System.IO;

using Thn;
using Thn.Collections;
#endregion

namespace Thn.Web
{
    /// <summary>
    /// Default implementation of <see cref="IFileManager"/>.
    /// </summary>
#if DEBUG || TESTING
    public
#else
    internal
#endif
 class FileManager : IFileManager
    {
        #region Fields
        Dictionary<string, FileToken> mTokens = new Dictionary<string, FileToken>();
        volatile object mSyncRoot = new object();
        #endregion

        #region Properties

        #region Content Path
        private string mContentPath;
        /// <summary>
        /// Gets or sets the local path where contents are located.
        /// </summary>
        public string ContentPath
        {
            get { return mContentPath; }
            set
            {
                if (value.EndsWith("\\")) value = value.Substring(0, value.Length - 1);
                mContentPath = value;
            }
        }
        #endregion

        #endregion

        #region Get Local Path
        /// <summary>
        /// Translate requested URI to local path.
        /// </summary>
        string GetLocalPath(string uri)
        {
            string result = string.Empty;

            //result = Path.Combine(mContentPath, uri);
            result = mContentPath + uri.Replace('/', '\\');

            return result;
        }
        #endregion

        #region Get Token
        /// <summary>
        /// Retrieve token of the provided uri. If cannot get, returns null.
        /// </summary>
        FileToken GetToken(string uri)
        {
            FileToken result = mTokens[uri];

            if (result == null)
            {
                //not exist? -> attempt to create one
                string localpath = GetLocalPath(uri);
                if (File.Exists(localpath))
                {
                    #region File exists -> create tokent
                    FileInfo fi = new FileInfo(localpath);
                    FileToken token = new FileToken()
                    {
                        LocalPath = localpath,
                        Uri = uri,
                        FileSize = fi.Length
                    };
                    lock (mSyncRoot)
                    {
                        mTokens[uri] = token;

                    }
                    result = token;

                    #endregion
                }
                else
                {
                    #region File does not exist -> skip processing

#if DEBUG
                    Log.Warning("Could not find content for URI: {0} - Local path: {1}", uri, localpath);
#endif

                    #endregion
                }
            }
            #region Defensive tracing
            else
            {
                //already found, move on
            }
            #endregion

            return result;
        }
        #endregion

        #region IFileManager Members

        #region Exists
        /// <summary>
        /// Checks whether the provided URI has an existing content.
        /// </summary>
        bool IFileManager.Exists(string uri)
        {
            return GetToken(uri) != null;
        }
        #endregion

        #region Read
        /// <summary>
        /// Attempt to reads a number of bytes into the provided buffer.
        /// </summary>
        /// <param name="uri">Unique URI of the file to read.</param>
        /// <param name="offset">Zero-based index of the starting offset from the beginning of file.</param>
        /// <param name="count">Number of bytes to read.</param>
        /// <param name="buffer">The buffer to store results in.</param>
        /// <returns>Actual number of bytes read. A negative value means an error has occurred.</returns>
        int IFileManager.Read(string uri, byte[] buffer, long offset, int count)
        {
            int result = 0;

            FileToken token = GetToken(uri);
            if (token != null)
            {
                #region Token found

                FileStream stream = null;
                try
                {
                    stream = new FileStream(token.LocalPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    stream.Seek(offset, SeekOrigin.Begin);
                    result = stream.Read(buffer, 0, count);
                }
                catch (Exception ex)
                {
                    ///signifies that en error has occurred.
                    result = -1;
                    Log.Error(ex);
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                    }
                }

                #endregion
            }
            #region Defensive tracing
            else
            {
                //token not found, skip
            }
            #endregion

            return result;
        }
        #endregion

        #region Complete
        /// <summary>
        /// Notify that a content is no longer required.
        /// Serving threads should call this method after it has completed processing so that the manager has a chance to
        /// clean up the cache used for the content.
        /// </summary>
        void IFileManager.Complete(string uri)
        {
            //this feature is not yet supported.
        }
        #endregion

        #region Get Size
        /// <summary>
        /// Gets size of a content in bytes.
        /// </summary>
        long IFileManager.GetSize(string uri)
        {
            FileToken token = GetToken(uri);
            return token != null ? token.FileSize : 0;
        }
        #endregion

        #endregion

        #region Constructors
        /// <summary>
        /// Default constructor.
        /// </summary>
        public FileManager()
        { }
        #endregion

        #region Inner Class - File Token
        class FileToken
        {
            public string Uri;
            public string LocalPath;
            public long FileSize;
        }
        #endregion
    }
}
